package com.example.ccj.b.a;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.example.ccj.R;
import com.example.ccj.b.c.dialog.SureOrCancelDialog;
import com.example.ccj.u.map.LocationUtil;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.StringUtils;
import com.example.ccj.u.ToastUtils;


import java.text.DecimalFormat;

/**
 * 打开地图获取经纬度  点选或者定位
 * 返回给调用窗口 《9》 setResult
 * 返回的数据是GPS经纬度
 */
public class LocationMapActivity extends AppCompatActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener, AMapLocationListener, LocationSource {
    private static final String TAG = "获取经纬度地图Activity:";
    private MapView mMapView = null;
    private AMap aMap;
    private UiSettings mUiSettings;
    String jingweidus;
    private TextView jw,mTvStopLocation,mTvok,mTvDynamicLocation;
    private int resultId;
    public static final String RESULT_SELECTED_LOCATION = "location";
    public static final int RESULT_LOCATION_CODE = 10233;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location_map);

        requestPermission();
        init(savedInstanceState);
    }

    private void init(Bundle savedInstanceState){
        AMapLocationClient.updatePrivacyShow(this, true, true);
        AMapLocationClient.updatePrivacyAgree(this, true);
        mTvStopLocation = findViewById(R.id.map_location_stop_location);
        mTvok = findViewById(R.id.map_location_queding);
        jw = findViewById(R.id.map_location_jingweidu);
        mTvDynamicLocation = findViewById(R.id.map_location_stop_dynamic_location);


        LatLng latLng = null;
        if (getIntent().getExtras() == null) {
            LogUtils.e(TAG,"未传入经纬度");
        } else {
            if (getIntent().getExtras().containsKey("location") && getIntent().getExtras().getString("location") != null) {
                String location = getIntent().getExtras().getString("location");
                String[] lo = location.split(",");
                if (lo.length == 2) {
                    try {
                        double lag = Double.parseDouble(lo[0]);
                        double lon = Double.parseDouble(lo[1]);
                        latLng = LocationUtil.gpsToGaoDe(this,lon,lag);
                    }catch (Exception e){
                        ToastUtils.showShort("经纬度格式错误：" + location);
                    }
                }
            }
            if (getIntent().getExtras().containsKey("resultId")) {
                resultId = getIntent().getExtras().getInt("resultId");
            }
        }

        mTvok.setOnClickListener(this);
        //获取地图控件引用
        mMapView = findViewById(R.id.map_location_1);

//        mEtSouSuo = findViewById(R.id.map_gaode_sousuo);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);

        //初始化地图控制器对象
        if (aMap == null) {
            aMap = mMapView.getMap();
            //初始点坐标及地图级别
            if (latLng != null) {
                addOneMarker("",latLng.longitude,latLng.latitude,null);
                aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(
                        latLng, 18, 0, 0)));
            }

            mUiSettings = aMap.getUiSettings();
            mUiSettings.setScaleControlsEnabled(true);
            mUiSettings.setZoomControlsEnabled(false);
            mUiSettings.setCompassEnabled(true);
            aMap.setLocationSource(this);// 设置定位监听
            mUiSettings.setMyLocationButtonEnabled(true);

            aMap.setOnMapLongClickListener(new AMap.OnMapLongClickListener() {
                @Override
                public void onMapLongClick(LatLng latLng) {
                    double[] GPS1 = LocationUtil.gaoDeToGps(latLng.longitude,latLng.latitude);

                    DecimalFormat df = new DecimalFormat("0.000000");
                    jingweidus = df.format(GPS1[0])+","+df.format(GPS1[1])+","+address;
                    jw.setText(GPS1[0]+","+GPS1[1]);
                    aMap.clear();
                    addOneMarker(GPS1[0]+","+GPS1[1],latLng.longitude,latLng.latitude,null);
                }
            });
        }

        mTvStopLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mlocationClient.stopLocation();
            }
        });

        mTvDynamicLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mlocationClient.startLocation();
            }
        });
    }

    //启动该activity返回数据至fragment的回调函数
    public static void start(String location, androidx.fragment.app.Fragment fragment, int requestCode) {
        Intent intent = new Intent(fragment.getContext(), LocationMapActivity.class);
        intent.putExtra("location",location);
        fragment.startActivityForResult(intent, requestCode);
    }

    public void addOneMarker(String title, double longitude, double latitude, String only){
        LatLng desLatLng = new LatLng(latitude,longitude);

        //点样式
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
        markerOption.position(desLatLng);
        markerOption.title(title);
        markerOption.draggable(true);
        markerOption.visible(true);

        Marker marker = aMap.addMarker(markerOption);
        //显示点信息
        marker.showInfoWindow();
//        moveMap(desLatLng, 17, 45, 0);
    }

    private LocationSource.OnLocationChangedListener mListener;
    private AMapLocationClientOption mLocationOption;
    private AMapLocationClient mlocationClient;
    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            try {
                mlocationClient = new AMapLocationClient(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式s
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.Sport);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    String address;
    private GeocodeSearch geocoderSearch;
    @SuppressLint("SetTextI18n")
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        try {
            geocoderSearch =new GeocodeSearch(LocationMapActivity.this);
        } catch (AMapException e) {
            e.printStackTrace();
        }
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {

//                myLog.d("测试定位","定位结果来源:"+aMapLocation.getLocationType());
//                myLog.d("测试定位","纬度:"+aMapLocation.getLatitude());
//                myLog.d("测试定位","经度:"+aMapLocation.getLongitude());
//                myLog.d("测试定位","精度信息:"+aMapLocation.getAccuracy());
//                myLog.d("测试定位","地址:"+aMapLocation.getAddress());
//                myLog.d("测试定位","国家:"+aMapLocation.getCountry());
//                myLog.d("测试定位","省:"+aMapLocation.getProvince());
//                myLog.d("测试定位","城市:"+aMapLocation.getCity());
                address = aMapLocation.getAddress();

                if (StringUtils.isEmpty(address)) {

                    if (StringUtils.isEmpty(aMapLocation.getCity())) {
                        LatLonPoint point = new LatLonPoint(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                        RegeocodeQuery query = new RegeocodeQuery(point, 200, GeocodeSearch.AMAP);
                        geocoderSearch.getFromLocationAsyn(query);
                        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
                            @Override
                            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                                String adCode = regeocodeResult.getRegeocodeAddress().getAdCode();
                                String cityCode = regeocodeResult.getRegeocodeAddress().getCityCode();
                                String formatAddress = regeocodeResult.getRegeocodeAddress().getFormatAddress();
//                                myLog.d("测试定位", "定位结果来源1:" + regeocodeResult.getRegeocodeAddress().getCity());
//                                myLog.d("测试定位", "定位结果来源2:" + regeocodeResult.getRegeocodeAddress().getCountry());
//                                myLog.d("测试定位", "定位结果来源3:" + regeocodeResult.getRegeocodeAddress().getProvince());
//                                myLog.d("测试定位", "定位结果来源4:" + regeocodeResult.getRegeocodeAddress().getFormatAddress());
//                                myLog.d("测试定位", "定位结果来源5:" + regeocodeResult.getRegeocodeAddress().getTowncode());
//                                myLog.d("测试定位", "定位结果来源6:" + regeocodeResult.getRegeocodeAddress().getDistrict());
//                                myLog.d("测试定位", "定位结果来源7:" + regeocodeResult.getRegeocodeAddress().getBuilding());
                                address = regeocodeResult.getRegeocodeAddress().getFormatAddress();
                            }

                            @Override
                            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

                            }
                        });
                    }
                }
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
//                LatLng la = new LatLng(aMapLocation.getLatitude(),aMapLocation.getLongitude());
//                aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(
//                        latLng, 13, 30, 30)));
                double[] GPS1 = LocationUtil.gaoDeToGps(aMapLocation.getLongitude(),aMapLocation.getLatitude());

                DecimalFormat df = new DecimalFormat("0.000000");
                jingweidus = df.format(GPS1[0])+","+df.format(GPS1[1])+","+address;

                jw.setText(GPS1[0]+","+GPS1[1]);
//                ToastUtil.ShowNowMsg(getApplicationContext(),aMapLocation.getLatitude()+","+aMapLocation.getLongitude()+"\n"
//                        +GPS1[0]+GPS1[1]+"\n"+aMapLocation.getAddress());
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode()+ ": " + aMapLocation.getErrorInfo();
                Log.e("AmapErr",errText);
            }
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        if (mMapView != null) mMapView.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        if (mMapView != null) mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        if (mMapView != null) mMapView.onPause();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        if (mMapView != null) mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {

    }


    @Override
    public void onClick(View view) {
        if (jingweidus == null) {
            ToastUtils.showShort("未获取到经纬度，请先定位！！！");
            return;
        }
        SureOrCancelDialog dialog = new SureOrCancelDialog(this);
        dialog.setCenterText("已获取到经纬度\r\n" + jingweidus + "是否使用？");
        dialog.setButtonSureText("确认").setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra(RESULT_SELECTED_LOCATION, jingweidus);
                setResult(RESULT_LOCATION_CODE, intent);
                finish();
            }
        });

        dialog.setButtonCancelText("重新选择").setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();

    }

    private void requestPermission() {
        // checkSelfPermission() 检测权限
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //TODO 申请存储权限
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,android.Manifest.permission.ACCESS_FINE_LOCATION},
                    PERMISSION_REQUEST_CODE);
        }
    }

    private static final int PERMISSION_REQUEST_CODE = 999;


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            //用户点击了“确定” == grantResults[0] == PackageManager.PERMISSION_GRANTED)
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.i("TAG", "onRequestPermissionsResult granted");
            } else {
                Log.i("TAG", "onRequestPermissionsResult denied");
                // TODO 用户拒绝权限申请，则弹出警示框
                showWaringDialog();
            }
        }
    }


    /**
     * 用户拒绝权限的警示
     */
    private void showWaringDialog() {
        new AlertDialog.Builder(this)
                .setTitle("警告！")
                .setMessage("请前往设置->应用->权限管理->打开存储权限，否则无法正常使用！")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //TODO 一般情况下如果用户不授权的话，功能时无法运行的，则直接退出
                        finish();
                    }
                }).show();
    }



}